<template>
  <div
    id="codeEditor-container"
    ref="codeEditorRef"
    style="min-height: 400px"
  ></div>
</template>

<script setup lang="ts">
import * as monaco from "monaco-editor";
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution";
import "monaco-editor/esm/vs/basic-languages/java/java.contribution";
import { withDefaults, defineProps, onMounted, ref, toRaw, watch } from "vue";

const codeEditorRef = ref();
const codeEditor = ref();

/**
 * 定义组件属性类型
 */
interface Props {
  value: string;
  language: string;
  handleChange: (v: string) => void;
}

/**
 * 给组件指定初始值
 */
const props = withDefaults(defineProps<Props>(), {
  value: () => "",
  language: "java",
  handleChange: (v: string) => {
    console.log(v);
  },
});
/**
 * 当用户切换语言时，更改编辑器语言
 */
watch(
  () => props.language,
  () => {
    if (codeEditor.value) {
      monaco.editor.setModelLanguage(
        toRaw(codeEditor.value).getModel(),
        props.language
      );
    }
    console.log("in CodeEditor.vue ", props.language);
  }
);
/**
 * 用于初始化monacoEditor 并且监听value变化
 */
onMounted(() => {
  if (codeEditorRef.value != null) {
    codeEditor.value = monaco.editor.create(codeEditorRef.value, {
      value: props.value,
      language: "java",
      theme: "vs-dark",
      readOnly: false,
      minimap: {
        enabled: false,
      },
      automaticLayout: true,
    });
    // 编辑 监听内容变化
    codeEditor.value.onDidChangeModelContent(() => {
      props.handleChange(toRaw(codeEditor.value).getValue());
    });
  }
});
/**
 * 复位
 */
const reset = () => {
  if (codeEditor.value != null) {
    toRaw(codeEditor.value).setValue("");
  }
};
</script>

<style></style>
